package com.jsn.android.audio2.sample.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@Database(entities = arrayOf(Word::class), version = 1, exportSchema = false)
abstract class WordRoomDataBase : RoomDatabase() {
    abstract fun wordDao(): WordDao

    companion object {
        @Volatile
        private var instance: WordRoomDataBase? = null

        fun getInstance(context: Context, scope: CoroutineScope) =
            instance ?: synchronized(this) {
                instance ?: make(context, scope).also { instance = it }
            }

        private fun make(context: Context, scope: CoroutineScope): WordRoomDataBase = Room.databaseBuilder(
            context.applicationContext,
            WordRoomDataBase::class.java,
            "word_database"
        ).addCallback(WordDatabaseCallback(scope)).build()
    }

    private class WordDatabaseCallback(private val scope: CoroutineScope) :
        RoomDatabase.Callback() {
        override fun onOpen(db: SupportSQLiteDatabase) {
            super.onOpen(db)
            instance?.let { dataBase ->
                scope.launch {
                    populateDatabase(dataBase.wordDao())
                }
            }
        }

        suspend fun populateDatabase(wordDao: WordDao) {
            wordDao.deleteAll()
            val word = Word("hello").also { wordDao.insert(it) }
            Word("world").also { wordDao.insert(it) }
        }
    }
}